<?php
require_once(APPLICATION_PATH . '/controllers/ExtensionFrontController.php' );

class AdminController extends ExtensionFrontController
{

    public function init()
    {
        parent::init();
    }

	public function indexAction()
    {
        $this->auth = new Zend_Session_Namespace('Zend_Auth');
        if ($this->auth->logged){
			$this->_redirect( '/admin/links' );
        }
    	
		$this->view->h1 = 'Nutrisimo - Administrador de contenidos';
		
        $request = $this->getRequest();
        $form = new Nutri_Form_Login();
        if ($request->isPost()) {
            if ($form->isValid($request->getPost()))
			{
				$data = $form->getValues();
				
                $user = $data['user'];
                $password = $data['pass'];
                $model  = new Nutri_Model_Login();
                $resultModel = $model->fetchRow(
                	$model->select()
                		->where('user = ?', $user)
                );
                $id = $resultModel->getId();

				if(!is_null($user))
				{
					if(($resultModel->getUser() == $user) and ($resultModel->getPass() == md5($password)))
					{
						$this->auth->id = $id;
						$this->auth->logged = true;
						$this->_redirect('/admin/links');
					}
				}
                $this->view->error = "Usuario o contraseña incorrecto";
            }
        }
        $this->view->formLogin = $form;
    }
    
	public function logoutAction()
    {
    	$this->auth = new Zend_Session_Namespace('Zend_Auth');
        if ($this->auth->logged){
			unset( $this->auth );
            Zend_Session::destroy();
        }
		$this->_redirect( '/admin' );
    }

    public function linksAction()
    {
        $this->compruebaSesion();
    }
	
	public function menuesAction()
    {
    	$this->compruebaSesion();
        $this->view->h1 = 'Menues';
	
		$menu = new Nutri_Model_Menu();
		$resultMenu = $menu->fetchAll();
    	
    	if(empty($resultMenu)) {
    		$this->view->listMenues = NULL;
    	} else {
	    	$menuArray = array();
	    	foreach ($resultMenu as $itemMenu) {
	    		$itemMenuArray = array();
	    		$itemMenuArray['id'] = $itemMenu->getId();
	    		$itemMenuArray['Titulo'] = $itemMenu->getTitle();
	    		$itemMenuArray['Descripcion'] = $itemMenu->getDescription();
	    		$itemMenuArray['Fecha_de_fin'] = $itemMenu->getEnddate();
				$itemMenuArray['Precio'] = $itemMenu->getPrice();
				$itemMenuArray['Color'] = $itemMenu->getColor();
	    		
	    		$menuArray[] = $itemMenuArray;
	    	}
	    	
	    	$this->view->listMenues = self::setPaginator($menuArray);
    	}
    }
    
    public function savemenuAction()
    {
    	$this->compruebaSesion();
        $id = $this->getRequest()->getParam('id');
        $formMenu = new Nutri_Form_Menu(array('id' => $id));
		
		$request = $this->getRequest();
		
		$product = new Nutri_Model_Product();
		$products = $product->fetchAll(
			$product->select()
					->order('name')
		);
		$multiOptions = array();
		
		$pruductsInMenu = new Nutri_Products_InMenu($id);
		$selectInMenu = $pruductsInMenu->getInMenues();
    	
    	foreach ($products as $itemProduct) {
		    $multiOptions[$itemProduct->getId()] = $itemProduct->getName();
		}
		
		$menuCheckboxes = new Zend_Form_Element_MultiCheckbox('productId', array(
		    'multiOptions' => $multiOptions
		));
		
		if(!empty($id)){
			/* $menuCheckboxes->setLabel("Agregar los productos al Menu"); */
			$menuCheckboxes->setValue($selectInMenu);
			$formMenu->addElement($menuCheckboxes);
		}
		
		if ($request->isPost()) {
    		if (is_null($id) && $formMenu->isValid($request->getPost())) {
                $menu = new Nutri_Model_Menu($formMenu->getValues());
				$menu->save();
                $pruductsInMenu->setInMenues($menuCheckboxes->getValue(), $id);
				$this->_redirect('/admin/menues');
            } elseif (!is_null($id) && $formMenu->isValid($request->getPost())) {
				$menuArray = $formMenu->getValues();
				$menuArray['id'] = $id;
				$menu = new Nutri_Model_Menu($menuArray);
				$menu->save();
				$pruductsInMenu->setInMenues($menuCheckboxes->getValue(), $id);
				$formMenu = new Nutri_Form_Menu();
				$this->view->updateData = "Menu ACTUALIZADO Correctamente."; 
            }
        }
		
    	if (empty($id)) {
			$this->view->h1 = 'Menues - Nuevo menu';	
		} else {
			$this->view->h1 = 'Menues - Editar menu';
			$menu = new Nutri_Model_Menu();
			$menu->find($id);
			
			if (0 < $menu->getId() && !$formMenu->isErrors()) {
				$formMenu->populate($menu->toArray());
				
				$formatDate = Zend_Registry::get('config')->date->format;
				$date = new Zend_Date();
				$endDay = $menu->getEnddate();
				
				if (!empty($endDay)) {
					$date->set($endDay);	
				}
				$newDate = $date->toString($formatDate);
				$formMenu->getElement('enddate')->setValue($newDate);
			}
		}
			
		$this->view->formMenu = $formMenu;
    }

	public function deletemenuAction()
    {
    	$this->compruebaSesion();
    	$this->view->h1 = 'Menues - Menu borrado';
		
        $id = $this->getRequest()->getParam('id');
		$menu = new Nutri_Model_Menu();
		$menu->find($id);
		
		if(!empty($id)) {
			$menu->delete();
		}
    }
    
    public function productosAction()
    {
    	$this->compruebaSesion();
        $this->view->h1 = 'Productos';
	
		$product = new Nutri_Model_Product();
		$resultProduct = $product->fetchAll(
			$product->select()
					->order('name')
		);
    	
    	if(empty($resultProduct)) {
    		$this->view->listMenues = NULL;
    	} else {
	    	$productArray = array();
	    	foreach ($resultProduct as $itemProduct) {
	    		$itemProductArray = array();
	    		$itemProductArray['id'] = $itemProduct->getId();
	    		$itemProductArray['Nombre'] = $itemProduct->getName();
	    		$itemProductArray['Descripcion'] = $itemProduct->getDescription();
				$itemProductArray['Precio'] = $itemProduct->getPrice();
	    		
	    		$productArray[] = $itemProductArray;
	    	}
	    	
	    	$this->view->listProducts = self::setPaginator($productArray);
    	}
    }
    
    public function saveproductoAction()
    {
    	$this->compruebaSesion();
        $id = $this->getRequest()->getParam('id');
        $formProduct = new Nutri_Form_Product(array('id' => $id));
		
		$request = $this->getRequest();
		
		if ($request->isPost()) {
    		if (is_null($id) && $formProduct->isValid($request->getPost())) {
                $product = new Nutri_Model_Product($formProduct->getValues());
				$product->save();
		    	$this->_redirect('/admin/productos');                
            } elseif (!is_null($id) && $formProduct->isValid($request->getPost())) {
				$productArray = $formProduct->getValues();
				$productArray['id'] = $id;
				$product = new Nutri_Model_Product($productArray);
				$product->save();
				$formProduct = new Nutri_Form_Product();
				$this->view->updateData = "Producto ACTUALIZADO Correctamente."; 
            }
        }
		
    	if (empty($id)) {
			$this->view->h1 = 'Productos - Nuevo producto';	
		} else {
			$this->view->h1 = 'Productos - Editar producto';
			$product = new Nutri_Model_Product();
			$product->find($id);
			
			if (0 < $product->getId() && !$formProduct->isErrors()) {
				$formProduct->populate($product->toArray());
			}
		}
			
		$this->view->formProduct = $formProduct;
    }

	public function deleteproductoAction()
    {
    	$this->compruebaSesion();
    	$this->view->h1 = 'Productos - Producto borrado';
		
        $id = $this->getRequest()->getParam('id');
		$product = new Nutri_Model_Product();
		$product->find($id);
		
		if(!empty($id)) {
			$product->delete();
		}
    }

	public function novedadesAction()
    {
    	$this->compruebaSesion();
        $this->view->h1 = 'Novedades';
	
		$news = new Nutri_Model_News();
		$resultNews = $news->fetchAll();
    	if(empty($resultNews)) {
    		$this->view->listNews = NULL;
    	} else {
	    	$newsArray = array();
	    	foreach ($resultNews as $itemNews) {
	    		$itemNewsArray = array();
	    		$itemNewsArray['id'] = $itemNews->getId();
	    		$itemNewsArray['Titulo'] = $itemNews->getTitle();
				$itemNewsArray['Estracto'] = substr($itemNews->getText(), 0, 70) . '...';
	    		
	    		$newsArray[] = $itemNewsArray;
	    	}
	    	$this->view->listNews = self::setPaginator($newsArray);
    	}
    }
    
    public function savenovedadAction()
    {
    	$this->compruebaSesion();
        $id = $this->getRequest()->getParam('id');
        $formNews = new Nutri_Form_News(array('id' => $id));
		
		$request = $this->getRequest();
		
		if ($request->isPost()) {
    		if (is_null($id) && $formNews->isValid($request->getPost())) {
                $news = new Nutri_Model_News($formNews->getValues());
				$news->save();
		    	$this->_redirect('/admin/novedades');                
            } elseif (!is_null($id) && $formNews->isValid($request->getPost())) {
				$newsArray = $formNews->getValues();
				$newsArray['id'] = $id;
				$news = new Nutri_Model_News($newsArray);
				$news->save();
				$formNews = new Nutri_Form_News();
				$this->view->updateData = "Noticia ACTUALIZADA Correctamente."; 
            }
			
        }
		
    	if (empty($id)) {
			$this->view->h1 = 'Novedades - Nuevo articulo';
		} else {
			$this->view->h1 = 'Novedades - Editar articulo';
			$news = new Nutri_Model_News();
			$news->find($id);
			
			if (0 < $news->getId() && !$formNews->isErrors()) {
				$formNews->populate($news->toArray());
			}
		}
			
		$this->view->formNews = $formNews;
    }

	public function deletenovedadAction()
    {
    	$this->compruebaSesion();
    	$this->view->h1 = 'Novedades - Articulo borrado';
		
        $id = $this->getRequest()->getParam('id');
		$news = new Nutri_Model_News();
		$news->find($id);
		
		if(!empty($id)) {
			$news->delete();
		}
    }
    
	public function companyAction()
    {
		$this->compruebaSesion();
        $id = $this->getRequest()->getParam('id');
        $formCompany = new Nutri_Form_Company(array('id' => $id));
		
		$request = $this->getRequest();
		
		if ($request->isPost()) {
    		if (is_null($id) && $formCompany->isValid($request->getPost())) {
                $news = new Nutri_Model_Company($formCompany->getValues());
				$news->save();
		    	$this->_redirect('/admin');                
            } elseif (!is_null($id) && $formCompany->isValid($request->getPost())) {
				$newsArray = $formCompany->getValues();
				$newsArray['id'] = $id;
				$news = new Nutri_Model_Company($newsArray);
				$news->save();
				$formCompany = new Nutri_Form_Company();
				$this->view->updateData = "Datos de la empresa actualizados correctamente";
            }
			
        }
		
    	if (empty($id)) {
			$this->view->h1 = 'Principal - Datos de la Empresa';
		} else {
			$this->view->h1 = 'Principal - Datos de la Empresa';
			$news = new Nutri_Model_Company();
			$news->find($id);
			
			if (0 < $news->getId() && !$formCompany->isErrors()) {
				$formCompany->populate($news->toArray());
			}
		}
			
		$this->view->formCompany = $formCompany;
    }
    
    public function usersAction()
    {
    	$this->compruebaSesion();
    	$this->view->h1 = 'Clientes - Listado de clientes registrados';
    	$user = new Nutri_Model_User();
    	$searchForm = new Nutri_Form_SearchFilter();    	
    	
       if ($this->getRequest()->isGet()) {
            $formData = $this->_request->getParams();
            if(!empty($formData['query'])) {
	            if ($searchForm->isValid($formData)) {
	            	$itemToSearch = $searchForm->getElement('query')->getValue();          	
					$resultSearch = $user->fetchAll(
								$user->select()
									->where('fullname like ?', '%' . $itemToSearch . '%')
									->orWhere('email like ?', '%' . $itemToSearch . '%')
									->orWhere('addres like ?', '%' . $itemToSearch . '%')
									->orWhere('tel like ?', '%' . $itemToSearch . '%')
					);
					
	            }
            } else {
            	$resultSearch = $user->fetchAll();
            }
					
            if (!empty($resultSearch)) {
            	$dataUser = array();
            	foreach ($resultSearch as $dataResult) {
            		$temporaryDate = array();
            		$temporaryDate['Nombre'] = $dataResult->getFullname();
            		$temporaryDate['Email'] = $dataResult->getEmail();
            		$temporaryDate['Telefono'] = $dataResult->getTel();
            		$temporaryDate['Direccion'] = $dataResult->getAddres();
            		$temporaryDate['Id'] = $dataResult->getId();
            		
            		$dataUser[] = $temporaryDate;
            	}
            	
				$this->view->resultSearchForm = self::setPaginator($dataUser);
	
            } else {
            	$dataUser = "No hay datos para mostrar";
            	$this->view->resultSearchForm = $dataUser;
            }
       }
        $this->view->searchForm = $searchForm;
    }
	
	protected function setPaginator($arrayToUse)
    {
    	$config = Zend_Registry::get('config');
		$pageInitial = $config->page->currentpage;
		// current page
		$page = $this->_getParam('page', $pageInitial);
		// number of rows to display per page
		$registers_page = $config->page->maximumpage;
		// maximum number of pages to display in the pager
		$page_rank = $config->page->rank;
		
		$paginador = Zend_Paginator::factory($arrayToUse);
		$paginador->setItemCountPerPage($registers_page)
				  ->setCurrentPageNumber($page)
				  ->setPageRange($page_rank);

		return $paginador;
    }
}